<template>
  <div>
    <Card :bordered="false" dis-hover class="mt25">
      <Form
        ref="orderData"
        :model="orderData"
        :label-width="labelWidth"
        :label-position="labelPosition"
        class="tabform"
        @submit.native.prevent
        label-width="120"
      >
        <div class="acea-row">
          <FormItem :label="$t('page.order.date')+'：'">
            <DatePicker
                    :editable="false"
                    :clearable="true"
                    @on-change="onchangeTime"
                    :value="timeVal"
                    format="yyyy/MM/dd"
                    type="datetimerange"
                    placement="bottom-start"
                    placeholder=""
                    style="width: 250px"
                    class="mr30"
                    :options="options"
            ></DatePicker>
          </FormItem>
          <FormItem label="">
            <Input
                    v-model="orderData.real_name"
                    placeholder=""
                    element-id="name"
                    clearable
                    style="width:250px;"
                    maxlength="20"
            >
              <Select
                      v-model="orderData.field_key"
                      slot="prepend"
                      style="width:80px;"
                      default-label="all"
              >
                <Option value="ob">{{$t('page.stock.outbound_order_no')}}</Option>
                <Option value="sku">{{$t('page.order.sku')}}</Option>
              </Select>
            </Input>
          </FormItem>
          <FormItem :label="$t('page.stock.archiving_status')+'：'" >
            <Select
                v-model="orderData.archiving_status"
                clearable
                style="width:200px;"
            >
              <Option :value="0">{{ $t('page.stock.not_archiving') }}</Option>
              <Option :value="1">{{ $t('page.stock.waiting_settlement') }}</Option>
              <Option :value="2">{{ $t('page.stock.already_settlement') }}</Option>
            </Select>
          </FormItem>
          <FormItem :label="$t('page.stock.archiving_period')+'：'">
            <DatePicker
                type="month"
                :placeholder="$t('page.stock.select_date')"
                @on-change="onarchivingchangeTime"
                style="width: 260px;">
            </DatePicker>
          </FormItem>
          <FormItem :label="$t('page.stock.warehouse')+'：'">
            <Select
                v-model="orderData.warehouse_name"
                clearable
                style="width:200px;"
            >
              <Option
                  v-for="item in stockNameList"
                  :value="item.value"
                  :key="item.value"
              >{{ item.label }}</Option>
            </Select>
          </FormItem>
          <Button type="primary" @click="userSearchs" class="ml20">{{$t('page.order.search')}}</Button>
          <Button @click="reset" class="ml20">{{$t('page.order.reset')}}</Button>
        </div>
      </Form>
    </Card>

    <Card :bordered="false" dis-hover class="mt25" style="background: transparent;">
      <Row :gutter="16" style="display: flex; justify-content: space-between;width: 100%;">
        <Col span="12" v-for="(val, i) in shopifyHeaderListType" :key="i" style="background-color: white;display: flex; justify-content: center;

        border-radius: 1.2rem;">
          <div class="PicItem">
            <img style="width: 100%; height: 100%;object-fit: contain" :src="val.pic" alt="">
            <!--            <CountUp :end="val.count" :duration="3" :ref="'HeaderList'+i" v-font="24" />-->
          </div>
          <div style="padding-top: 1rem 0; margin: 10px;">
            <p class="titleItem">{{ val.name }}<Icon type="ios-play" size="15" color="#620E80"/></p>
            <p class="countItem">${{val.count}}</p>
<!--            <CountUp :end="val.count" :duration="3" :ref="'HeaderList'+i" v-font="24" />-->
          </div>
        </Col>
      </Row>
    </Card>

    <Card :bordered="true" dis-hover class="mt25">
      <!-- 平台订单-->
      <vxe-table
          border="inner"
          ref="xTable"
          height="600"
          class="mt25"
          :loading="loading"
          row-id="id"
          :expand-config="{accordion: true}"
          :checkbox-config="{reserve: true}"
          @checkbox-change="checkboxItem"
          :data="orderList">
        <vxe-column field="order_no" :title="$t('page.order.order_no')" min-width="100"></vxe-column>
        <vxe-column field="customer_name" v-if="infor.code.startsWith('B')" :title="$t('page.customer.customer_name')" min-width="190"></vxe-column>
        <vxe-column field="created_at" :title="$t('page.stock.creat_time')" min-width="190">
          <template v-slot="{ row }">
            <span>{{ formatTimeNative(row.created_at) }}</span> <!-- 调用格式化方法 -->
          </template>
        </vxe-column>
        <vxe-column field="sku" :title="$t('page.order.items')" min-width="330">
          <template v-slot="{ row }">
            <div slot="content">
              <div>
                <p>{{ row.name }}</p>
                <p> {{row.sku}}</p>
                <p class="tabBox_pice">{{ "$" + row.discounted_unit_price_set + " x " + row.quantity }}</p>
              </div>
            </div>
          </template>
        </vxe-column>
        <vxe-column field="warehouse_name" :title="$t('page.stock.stock_name')" min-width="90" >
          <template v-slot="{ row }">
            <span v-if="row.warehouse_name == '1791498718751334401'" >CA 5005</span>
            <span v-if="row.warehouse_name == '101816795504'" >Houston</span>
          </template>
        </vxe-column>
        <vxe-column field="discounted_total_set" :title="$t('page.order.pay_price')" min-width="190">
          <template v-slot="{ row }">
            <p class="tabBox_pice">
              <Numeral :value="row.discounted_total_set" format="0,0.00">
                <template #prefix>
                  <strong>$</strong>
                </template>
              </Numeral>
            </p>
          </template>
        </vxe-column>
        <vxe-column field="ob_no" :title="$t('page.stock.outbound_order_no')" min-width="190">
        </vxe-column>
        <vxe-column field="commission" :title="$t('page.order.service')+' '+$t('page.order.fee')" min-width="190">
          <template v-slot="{ row }">
            <p class="tabBox_pice">
              <Numeral :value="row.commission" format="0,0.00">
                <template #prefix>
                  <strong>$</strong>
                </template>
              </Numeral>
            </p>
          </template>
        </vxe-column>
        <vxe-column field="is_pay" :title="$t('page.order.payment')+' '+$t('page.order.status')" min-width="90" fixed="right">
          <template v-slot="{ row }">
            <Tag color="gold" v-if="row.is_pay == 0">{{ $t('page.order.unpaid') }}</Tag>
            <Tag color="green" v-if="row.is_pay == 1">{{ $t('page.order.paid') }}</Tag>
          </template>
        </vxe-column>
        <vxe-column field="is_mention" :title="$t('page.order.fulfillment')+' '+$t('page.order.status')" min-width="90" fixed="right">
          <template v-slot="{ row }">
            <Tag color="gold" v-if="row.is_mention == 1">{{ $t('page.order.fulfilled') }}</Tag>
            <Tag color="green" v-if="row.is_mention == 0">{{ $t('page.order.unfulfilled') }}</Tag>
          </template>
        </vxe-column>
        <vxe-column field="archiving_status" :title="$t('page.stock.archiving_status')" min-width="90" align="center" fixed="right">
          <template v-slot="{ row }">
            <span v-if="row.archiving_status == 0">{{$t('page.stock.not_archiving')}}</span>
            <span v-else-if="row.archiving_status == 1">{{$t('page.stock.waiting_settlement')}}</span>
            <span v-else-if="row.archiving_status == 2">{{$t('page.stock.already_settlement')}}</span>
          </template>
        </vxe-column>

        <vxe-column field="archiving_period" :title="$t('page.stock.archiving_period')" min-width="100" fixed="right"></vxe-column>

      </vxe-table>
      <div class="acea-row row-right mt15">
        <Page :total="total" :current="orderData.page" @on-change="pageChange"
              :page-size="orderData.limit"/>
      </div>
    </Card>
    <!-- 详情 -->
    <details-from
      ref="detailss"
      :orderDatalist="orderDatalist"
      :orderId="orderId"
	  :row-active="rowActive"
	  :formType="1"
    ></details-from>
  </div>
</template>

<script>
import { mapState } from "vuex";
import editFrom from "@/components/from/from";
import detailsFrom from "./components/orderDetails";
import userDetails from "@/components/userDetails/userDetails";
import timeOptions from "@/utils/timeOptions";
import util from "@/libs/util";
import Setting from "@/setting";
import exportExcel from "@/utils/newToExcel.js";
import orderPic2 from '@/assets/images/monery.png'
import orderPic3 from '@/assets/images/PlatformFees.png'
import {
  orderList, shopifyOrderList, orderHeaderInfo, orderAllHeaderInfo, orderShopifyHeaderInfo
} from "@/api/order";
export default {
  name: "index",
  components: {
    editFrom,
    detailsFrom,
    userDetails
  },
  data() {
    return {
      stockNameList: [
        {
          value: '1791498718751334401',
          label: 'CA 5005'
        },
        {
          value: '101816795504',
          label: 'Houston'
        }
      ],
      roterPre:Setting.roterPre,
      isAll: 0,
      isCheckBox: false,
      checkUidList:[],
      manualModal:false,
      timeVal: [],
      archivingTimeVal: [],
      options: timeOptions,
      headerList: [],
      payList: [
        { label: "全部", val: "" },
        { label: "微信支付", val: "1" },
        { label: "支付宝支付", val: "4" },
        { label: "余额支付", val: "2" },
        { label: "线下支付", val: "3" },
      ],
      // 订单列表
      orderData: {
        page: 1,
        limit: 10,
        type: "0",
        status: "",
        data: "",
        real_name: "",
        pay_type: "",
        field_key: "all",
        archiving_status:"",
        archiving_period:"",
      },
      orderList: [],
	  supplierInfo:{
		  id:0,
		  type:1,
	  },
      total: 0,
      thisOrderList: [],
      shopifyHeaderList: [],
      thisOrderTotal: 0,
      loading: false,
      orderConNum:0,
      orderConId:0,
      orderId: 0,
      infor:{},
      delfromData: {},
      rowActive: {},
      orderDatalist: null,
      FromData: null,
      file: "",
      uploadAction: `${Setting.apiBaseURL}/file/upload/1`,
      uploadHeaders: {},
      fileList: [],
      modals2: false,
      writeOffFrom: {
        code: "",
        confirm: 0,
      },
      exportListOn: 0,
      exportList: [
        {
          name: "1",
          label: "导出发货单",
        },
        {
          name: "0",
          label: "导出订单",
        },
      ],
    };
  },
  watch: {
    $route() {
      if (this.$route.fullPath === `${Setting.roterPre}/order/list?type=7&status=1`) {
        this.getPath();
      }
    }
  },
  computed: {
    ...mapState("store/layout", ["isMobile"]),
    labelWidth() {
      return this.isMobile ? undefined : 80;
    },
    labelPosition() {
      return this.isMobile ? "top" : "right";
    },
    shopifyHeaderListType(){
      var Total,Commission = 0
      for (let i = 0; i < this.shopifyHeaderList.length; i++) {
        if (this.shopifyHeaderList[i].type == 0) {
          Total = this.shopifyHeaderList[i].count
        }else if (this.shopifyHeaderList[i].type == 1) {
          Commission = this.shopifyHeaderList[i].count
        }
      }
      return [
        {type: 0, name:  $t('page.order.total'), count: Total,pic:orderPic2},
        {type: 1, name: $t('page.order.service')+$t('page.order.fee'), count: Commission,pic:orderPic3},
      ]
    },
  },
  created() {
    this.getHeader()
	this.getSupplierInfo();
  },
  mounted() {

  },
  methods: {
    // 具体日期
    onarchivingchangeTime(e) {
      this.archivingTimeVal = e;
      this.orderData.archiving_period = this.archivingTimeVal;
    },
    //头部统计
    getShopifyHeader() {
      this.loading = true;
      orderShopifyHeaderInfo(this.orderData).then((res) => {
        this.shopifyHeaderList = res.data.list;
      });
    },
    formatTimeNative(timestamp) {
      const date = new Date(timestamp);
      const now = new Date();
      const isToday =
          date.getDate() === now.getDate() &&
          date.getMonth() === now.getMonth() &&
          date.getFullYear() === now.getFullYear();

      // 时间格式（小时:分钟 + am/pm）
      const timeOptions = {
        hour: 'numeric',
        minute: '2-digit',
        hour12: true,
      };
      const timeString = new Intl.DateTimeFormat('en-US', timeOptions).format(date);

      return isToday ? `Today at ${timeString}` : new Intl.DateTimeFormat('en-US', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: 'numeric',
        minute: '2-digit',
        hour12: true,
      }).format(date);
    },
    //头部列表
    getHeader() {
      this.loading = true;
      orderHeaderInfo(this.orderData).then((res) => {
        this.headerList = res.data.list;
        this.getShopifyHeader();
        this.getList();
      });
    },
    //跳转刷新
    getPath() {
      this.orderData.page = 1;
      this.orderData.status = this.$route.query.status;
      this.getList();
    },
	allReset(){
	  this.isAll = 0;
	  this.isCheckBox = false;
	  this.$refs.xTable.setAllCheckboxRow(false);
	  this.checkUidList = [];
	},
	checkboxItem(e){
	  let id = parseInt(e.rowid);
	  let index = this.checkUidList.indexOf(id);
	  if(index !== -1){
	    this.checkUidList = this.checkUidList.filter((item)=> item !== id);
	  }else{
	    this.checkUidList.push(id);
	  }
	},
    printOreder(){
	  if (this.checkUidList.length > 10 || (this.isAll==1 && this.total>10)) {
	    return this.$Message.error('最多批量打印10个订单')
	  }
	  let ids = []
	  if (this.isAll==1 && this.total<=10){
	    this.orderList.forEach(item=>{
	      ids.push(parseInt(item.id))
	    })
	  }
      let pathInfo = this.$router.resolve({
        path:`${Setting.roterPre}/order/distribution`,
        query:{
		  id: this.isAll==1?ids.join(','):this.checkUidList.join(','),
        }
      });
      window.open(pathInfo.href, '_blank');
    },
	getSupplierInfo(){
		getSupplierInfo().then((res) => {
		  this.supplierInfo = res.data.info;
		});
	},
    reset(){
      this.timeVal = [];
      this.orderData = {
        page: 1,
        limit: 10,
        type: "",
        status: "",
        data: "",
        real_name: "",
        pay_type: "",
        archiving_status:"",
        archiving_period:""
      };
      this.getList();
      this.getShopifyHeader();
    },
    // 订单导出
    async exports(value) {
      this.exportListOn = this.exportList.findIndex(
              (item) => item.name === value
      );
      let [th, filekey, data, fileName] = [[], [], [], ""];
      let excelData = JSON.parse(JSON.stringify(this.orderData));
      excelData.page = 1;
      excelData.type = value;
      excelData.ids = this.checkUidList.join();
      for (let i = 0; i < excelData.page + 1; i++) {
        let lebData = await this.downOrderData(excelData);
        if (!fileName) fileName = lebData.filename;
        if (!filekey.length) {
          filekey = lebData.filekey;
        }
        if (!th.length) th = lebData.header;
        if (lebData.export.length) {
          data = data.concat(lebData.export);
          excelData.page++;
        } else {
          exportExcel(th, filekey, fileName, data);
          return;
        }
      }
    },
    downOrderData(excelData) {
      return new Promise((resolve, reject) => {
        storeOrderApi(excelData).then((res) => {
          return resolve(res.data);
        });
      });
    },
    // 编辑
    edit(row) {
      this.getOrderData(row.id);
    },

    // 修改成功
    submitFail() {
      this.getList();
      if(this.orderConNum !=1){
        this.getData(this.orderId,1);
      }else{
        this.$refs.detailss.getSplitOrder(this.orderConId);
      }
    },
    // 操作
    changeMenu(row, name, num) {
      this.orderId = row.id;
      this.orderConId = row.pid>0?row.pid:row.id;
      this.orderConNum = num;
      switch (name) {
        case "1":
          this.delfromData = {
            title: "修改立即支付",
            url: `/order/pay_offline/${row.id}`,
            method: "post",
            ids: "",
          };
          this.$modalSure(this.delfromData)
                  .then((res) => {
                    this.$Message.success(res.msg);
                    this.getData(row.id,1);
                    this.getList();
                  })
                  .catch((res) => {
                    this.$Message.error(res.msg);
                  });
          break;
        case "2":
          this.rowActive = row;
          this.getData(row.id);
          break;
        case "3":
          this.$refs.record.modals = true;
          this.$refs.record.getList(row.id);
          break;
        case "4":
          this.$refs.remarks.formValidate.remark = row.remark;
          this.$refs.remarks.modals = true;
          break;
        case "5":
          this.getOnlyRefundData(row.id, row.refund_type);
          break;
        case "55":
          this.getRefundData(row.id, row.refund_type);
          break;
        case "6":
          this.getRefundIntegral(row.id);
          break;
        case "7":
          this.getNoRefundData(row.id);
          break;
        case "8":
          this.delfromData = {
            title: "修改确认收货",
            url: `/order/take/${row.id}`,
            method: "put",
            ids: "",
          };
          this.$modalSure(this.delfromData)
                  .then((res) => {
                    this.$Message.success(res.msg);
                    this.getList();
                    if(num){
                      this.$refs.detailss.getSplitOrder(row.pid)
                    }else{
                      this.getData(row.id,1);
                    }
                  })
                  .catch((res) => {
                    this.$Message.error(res.msg);
                  });
          break;
        case "10":
          this.delfromData = {
            title: "立即打印订单",
            info: "您确认打印此订单吗?",
            url: `/order/print/${row.id}`,
            method: "get",
            ids: "",
          };
          this.$modalSure(this.delfromData)
                  .then((res) => {
                    this.$Message.success(res.msg);
                    this.getList();
                  })
                  .catch((res) => {
                    this.$Message.error(res.msg);
                  });
          break;
        case "11":
          this.delfromData = {
            title: "立即打印电子面单",
            info: "您确认打印此电子面单吗?",
            url: `/order/order_dump/${row.id}`,
            method: "get",
            ids: "",
          };
          this.$modalSure(this.delfromData)
                  .then((res) => {
                    this.$Message.success(res.msg);
                    this.getList();
                  })
                  .catch((res) => {
                    this.$Message.error(res.msg);
                  });
          break;
        case "12":
          let pathInfo = this.$router.resolve({
            path:`${Setting.roterPre}/order/distribution`,
            query:{
              id:row.id
            }
          });
          window.open(pathInfo.href, '_blank');
          break;
        default:
          this.delfromData = {
            title: "删除订单",
            url: `/order/del/${row.id}`,
            method: "DELETE",
            ids: "",
          };
          this.delOrder(row, this.delfromData);
      }
    },
    // 获取详情表单数据
    getData(id,type) {
      getDataInfo(id)
              .then(async (res) => {
                if(!type){
                  this.$refs.detailss.modals = true;
                }
                this.$refs.detailss.activeName = 'detail';
                this.orderDatalist = res.data;
                if (this.orderDatalist.orderInfo.refund_reason_wap_img) {
                  try {
                    this.orderDatalist.orderInfo.refund_reason_wap_img = JSON.parse(
                            this.orderDatalist.orderInfo.refund_reason_wap_img
                    );
                  } catch (e) {
                    this.orderDatalist.orderInfo.refund_reason_wap_img = [];
                  }
                }
              })
              .catch((res) => {
                this.$Message.error(res.msg);
              });
    },

    getList(){
      this.loading = true;
      shopifyOrderList(this.orderData).then(res=>{
        let data = res.data;
        this.$set(this,'orderList',data.list);
        this.total = res.data.count;
        this.loading = false;
		this.$nextTick(function(){
		  if (this.isAll == 1) {
		    if(this.isCheckBox){
		      this.$refs.xTable.setAllCheckboxRow(true);
		    }else{
		      this.$refs.xTable.setAllCheckboxRow(false);
		    }
		  }else{
			let obj = this.$refs.xTable.getCheckboxReserveRecords(true);
			if(!this.checkUidList.length || this.checkUidList.length <= obj.length){
			  this.$refs.xTable.setAllCheckboxRow(false);
			}
		  }
		})
      }).catch(err=>{
        this.loading = false;
        this.$Message.error(err.msg)
      })
    },
    getThisOrderList(){
      this.loading = true;
      orderList(this.orderData).then(res=>{
        let data = res.data;
        this.$set(this,'thisOrderList',data.list);
        this.thisOrderTotal = res.data.count;
        this.loading = false;
      }).catch(err=>{
        this.loading = false;
        this.$Message.error(err.msg)
      })
    },
    // 具体日期
    onchangeTime(e) {
      if (e[1].slice(-8) === "00:00:00") {
        e[1] = e[1].slice(0, -8) + "23:59:59";
        this.timeVal = e;
      } else {
        this.timeVal = e;
      }
      this.orderData.data = this.timeVal[0] ? this.timeVal.join("-") : "";
      this.orderData.page = 1;
	    // this.allReset();
      // this.getList();
    },
    pageChange(index) {
      this.orderData.page = index;
      this.getList();
    },
    userSearchs(){
	    this.allReset();
      this.orderData.page = 1;
      // this.getList();
      this.getHeader();
      this.getShopifyHeader();
    }
  },
  async mounted () {
    let storage=window.localStorage;
    let value = storage.getItem('userInfoSupplier')
    this.infor = JSON.parse(value);
    this.infor.code
  }
};
</script>

<style lang="stylus" scoped>
.ivu-col-span-12{
  flex: 0 0 49.5% !important;
}
.PicItem{
  height 5rem;
  width: 10rem;
  margin: 0.5rem 0;
}
.titleItem{
  font-size: 1.2rem;
  font-weight: bold;
  color: black;
}
.countItem{
  font-size: 2rem;
  font-weight: bold;
  color: #630F81;
}
.todayItem{
  font-size: 1.1rem;
  font-weight: bold;
  color: #B167CA;
}
  .tdinfo{
    margin-left: 75px;
    margin-top: 16px;
  }
  .expand-row{
    margin-bottom: 16px;
    font-size: 12px;
  }
  .tabBox {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;

    .tabBox_img {
      width: 30px;
      height: 30px;

      img {
        width: 100%;
        height: 100%;
      }
    }

    .tabBox_tit {
      width:267px;
      height:30px;
      line-height:30px;
      font-size: 12px !important;
      margin: 0 2px 0 10px;
      letter-spacing: 1px;
      box-sizing: border-box;
    }
  }
  .tabBox +.tabBox{
    margin-top:5px;
  }
</style>
